<template>
  <div class="box">
    <van-pull-refresh v-model="isLoading" :success-text="tipText" success-duration="3000" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >

        <article-item v-for="item in list" :key="item.art_id+''" :info="item" />
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getarticles } from '@/api/article.js'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  components: { ArticleItem },
  props: {
    channels: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      error: false,
      isLoading: false,
      tipText: ''
    }
  },

  created() {

  },

  methods: {
    async onLoad() {
      try {
        const res = await getarticles({
          channel_id: this.channels,
          timestamp: this.timestamp,
          with_top: 1
        })
        // console.log(res)
        this.list.push(...res.results)
        this.timestamp = res.pre_timestamp
        this.loading = false
        if (res.results.length === 0) {
          this.finished = true
        }
      } catch (err) {
        // console.log(err)
        this.err = true
        this.loading = true
      }

      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求

      // 加载状态结束

      // 数据全部加载完成
    },
    async onRefresh() {
      try {
        const res = await getarticles({
          channel_id: this.channels,
          timestamp: Date.now(),
          with_top: 1
        })
        this.list.unshift(...res.results)
        this.isLoading = false
        this.tipText = '刷新成功'
      } catch (err) {
        // console.log(err)
        this.isLoading = false
        this.tipText = '刷新失败'
      }
    }
  }
}
</script>

<style scoped lang='less'>
.box{
  height: 80vh;
  overflow-y: scroll;
}
</style>
